package com.pzhu.record.controller;

import com.pzhu.record.constants.Constant;
import com.pzhu.record.entity.Basicinformation;
import com.pzhu.record.entity.Teacher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 不同角色登录控制类
 *
 * @author Zhou YuSen
 * @date 2020/4/2 17:05
 */
@Controller
@RequestMapping("/login")
public class LoginController extends BaseAction {

    /**
     * 实现登录功能
     *
     * @return
     */
    @RequestMapping("/login")
    public String login(String userId, String password, String role, HttpSession session, HttpServletRequest request) {

        if (userId != null && password != null && role != null) {
            //判断角色编号，是教师还是学生
            if (role.equals(Constant.TEACHER_ROLE)) {
                //角色为教师
                Teacher teacher = teacherService.selectByIdOrpass(userId, password);
                if (teacher != null) {
                    //登陆成功
                    //保存到session
                    session.setAttribute("userInfo", teacher);
                    return "index";
                } else {

                    //登陆失败
                    request.setAttribute("message", "用户名或密码错误！");
                    return "forward:/login.jsp";
                }

            } else if (role.equals(Constant.Student_ROLE)) {
                //角色为学生
                Basicinformation basicinformation = basicinformationService.selectByIdOrpass(userId, password);
                if (basicinformation != null) {
                    //登陆成功
                    //保存到session
                    session.setAttribute("userInfo", basicinformation);
                    return "index";
                } else {

                    //登陆失败
                    request.setAttribute("message", "用户名或密码错误！");
                    return "forward:/login.jsp";
                }

            }

        }
        request.setAttribute("message", "用户名或密码不能为空！");
        return "forward:/login.jsp";
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.removeAttribute("userInfo");
        return "login";
    }

}

